package com.education.platform.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.education.platform.dto.teacher.AdminTeacherQueryDTO;
import com.education.platform.dto.teacher.AuditIdentityDTO;
import com.education.platform.dto.teacher.TeacherQueryDTO;
import com.education.platform.entity.User;
import com.education.platform.entity.UserIdentity;
import com.education.platform.entity.UserProfile;
import com.education.platform.exception.BusinessException;
import com.education.platform.mapper.UserIdentityMapper;
import com.education.platform.mapper.UserMapper;
import com.education.platform.mapper.UserProfileMapper;
import com.education.platform.service.TeacherService;
import com.education.platform.common.ResultCode;
import com.education.platform.vo.teacher.TeacherDetailVO;
import com.education.platform.vo.teacher.TeacherListVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 教员服务实现类
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class TeacherServiceImpl implements TeacherService {

    private final UserMapper userMapper;
    private final UserProfileMapper userProfileMapper;
    private final UserIdentityMapper userIdentityMapper;

    @Override
    public Map<String, Object> getTeacherList(TeacherQueryDTO queryDTO) {
        // 构建分页对象
        Page<User> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());

        // 构建查询条件
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getStatus, "ACTIVE");
        userWrapper.like(User::getRoles, "TEACHER");

        // 按创建时间倒序
        userWrapper.orderByDesc(User::getCreatedAt);

        // 查询用户基本信息
        Page<User> userPage = userMapper.selectPage(page, userWrapper);
        List<User> users = userPage.getRecords();

        if (users.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("list", new ArrayList<>());
            result.put("total", 0);
            result.put("page", queryDTO.getPage());
            result.put("size", queryDTO.getSize());
            return result;
        }

        // 获取用户ID列表
        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());

        // 批量查询用户详细资料
        Map<Long, UserProfile> profileMap = new HashMap<>();
        List<UserProfile> profiles = userProfileMapper.selectList(
            new LambdaQueryWrapper<UserProfile>().in(UserProfile::getUserId, userIds)
        );
        profiles.forEach(profile -> profileMap.put(profile.getUserId(), profile));

        // 批量查询认证状态
        Map<Long, UserIdentity> identityMap = new HashMap<>();
        List<UserIdentity> identities = userIdentityMapper.selectList(
            new LambdaQueryWrapper<UserIdentity>().in(UserIdentity::getUserId, userIds)
        );
        identities.forEach(identity -> identityMap.put(identity.getUserId(), identity));

        // 组装教员列表VO
        List<TeacherListVO> teacherList = users.stream().map(user -> {
            TeacherListVO vo = new TeacherListVO();
            UserProfile profile = profileMap.get(user.getId());
            UserIdentity identity = identityMap.get(user.getId());

            vo.setId(user.getId());
            vo.setAvatarUrl(user.getAvatarUrl());
            vo.setCreatedAt(user.getCreatedAt());
            vo.setIsOnline(false); // TODO: 从Redis获取在线状态
            vo.setVerified(identity != null && "APPROVED".equals(identity.getStatus()));

            if (profile != null) {
                vo.setRealName(profile.getRealName());
                vo.setSchool(profile.getSchool());
                vo.setEducation(profile.getEducation());
                vo.setIntro(profile.getIntro());
                vo.setExperienceYears(profile.getExperienceYears());
                vo.setHourlyRate(profile.getHourlyRate() != null ? profile.getHourlyRate() : BigDecimal.ZERO);

                // 处理年级
                if (StrUtil.isNotBlank(profile.getGrades())) {
                    try {
                        // 如果是JSON格式
                        if (profile.getGrades().startsWith("[")) {
                            vo.setGrades(JSONUtil.toList(profile.getGrades(), String.class));
                        } else {
                            // 如果是逗号分隔
                            vo.setGrades(Arrays.asList(profile.getGrades().split(",")));
                        }
                    } catch (Exception e) {
                        vo.setGrades(new ArrayList<>());
                    }
                } else {
                    // 默认支持所有年级
                    vo.setGrades(Arrays.asList("小学", "初中", "高中", "大学", "成人"));
                }
                
                // 处理科目
                if (StrUtil.isNotBlank(profile.getSubjects())) {
                    vo.setSubjects(Arrays.asList(profile.getSubjects().split(",")));
                } else {
                    vo.setSubjects(new ArrayList<>());
                }
            }

            // TODO: 从订单表统计评分和订单数
            vo.setRating(BigDecimal.valueOf(4.8));
            vo.setReviewCount(100);
            vo.setOrderCount(50);

            return vo;
        }).collect(Collectors.toList());

        // 应用筛选条件
        teacherList = applyFilters(teacherList, queryDTO);

        // 返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("list", teacherList);
        result.put("total", userPage.getTotal());
        result.put("page", queryDTO.getPage());
        result.put("size", queryDTO.getSize());
        result.put("pages", userPage.getPages());

        return result;
    }

    @Override
    public TeacherDetailVO getTeacherDetail(Long id) {
        // 查询用户基本信息
        User user = userMapper.selectById(id);
        if (user == null || !"ACTIVE".equals(user.getStatus())) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }

        // 检查是否是教员
        if (!user.getRoles().contains("TEACHER")) {
            throw new BusinessException("该用户不是教员");
        }

        // 查询用户详细资料
        UserProfile profile = userProfileMapper.selectOne(
            new LambdaQueryWrapper<UserProfile>().eq(UserProfile::getUserId, id)
        );

        // 查询认证状态
        UserIdentity identity = userIdentityMapper.selectOne(
            new LambdaQueryWrapper<UserIdentity>().eq(UserIdentity::getUserId, id)
        );

        // 组装详情VO
        TeacherDetailVO vo = new TeacherDetailVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setAvatarUrl(user.getAvatarUrl());
        vo.setEmail(user.getEmail());
        vo.setCreatedAt(user.getCreatedAt());
        vo.setIsOnline(false); // TODO: 从Redis获取
        vo.setVerified(identity != null && "APPROVED".equals(identity.getStatus()));
        vo.setIdentityStatus(identity != null ? identity.getStatus() : "NOT_SUBMITTED");

        // 手机号脱敏
        if (StrUtil.isNotBlank(user.getMobile())) {
            vo.setMobile(user.getMobile().replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2"));
        }

        if (profile != null) {
            vo.setRealName(profile.getRealName());
            vo.setGender(profile.getGender());
            vo.setBirthday(profile.getBirthday());
            vo.setCity(profile.getCity());
            vo.setSchool(profile.getSchool());
            vo.setEducation(profile.getEducation());
            vo.setIntro(profile.getIntro());
            vo.setExperienceYears(profile.getExperienceYears());
            vo.setHourlyRate(profile.getHourlyRate());

            if (StrUtil.isNotBlank(profile.getSubjects())) {
                vo.setSubjects(Arrays.asList(profile.getSubjects().split(",")));
            }
        }

        // TODO: 从订单表统计数据
        vo.setRating(BigDecimal.valueOf(4.8));
        vo.setReviewCount(100);
        vo.setOrderCount(50);
        vo.setStudentCount(30);

        return vo;
    }

    @Override
    public List<TeacherListVO> getRecommendTeachers(Integer limit) {
        // 查询评分高、订单多的教员
        TeacherQueryDTO queryDTO = new TeacherQueryDTO();
        queryDTO.setPage(1);
        queryDTO.setSize(limit);
        queryDTO.setSortBy("rating");
        queryDTO.setSortOrder("DESC");

        Map<String, Object> result = getTeacherList(queryDTO);
        return (List<TeacherListVO>) result.get("list");
    }

    @Override
    public Map<String, Object> adminGetTeachers(AdminTeacherQueryDTO queryDTO) {
        Page<User> page = new Page<>(queryDTO.getPage(), queryDTO.getSize());

        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.like(User::getRoles, "TEACHER");

        // 关键词查询
        if (StrUtil.isNotBlank(queryDTO.getKeyword())) {
            userWrapper.and(w -> w
                .like(User::getUsername, queryDTO.getKeyword())
                .or().like(User::getMobile, queryDTO.getKeyword())
            );
        }

        // 状态查询
        if (StrUtil.isNotBlank(queryDTO.getStatus())) {
            userWrapper.eq(User::getStatus, queryDTO.getStatus());
        }

        userWrapper.orderByDesc(User::getCreatedAt);

        Page<User> userPage = userMapper.selectPage(page, userWrapper);
        List<User> users = userPage.getRecords();

        if (users.isEmpty()) {
            Map<String, Object> result = new HashMap<>();
            result.put("list", new ArrayList<>());
            result.put("total", 0);
            return result;
        }

        List<Long> userIds = users.stream().map(User::getId).collect(Collectors.toList());

        Map<Long, UserProfile> profileMap = new HashMap<>();
        List<UserProfile> profiles = userProfileMapper.selectList(
            new LambdaQueryWrapper<UserProfile>().in(UserProfile::getUserId, userIds)
        );
        profiles.forEach(profile -> profileMap.put(profile.getUserId(), profile));

        Map<Long, UserIdentity> identityMap = new HashMap<>();
        List<UserIdentity> identities = userIdentityMapper.selectList(
            new LambdaQueryWrapper<UserIdentity>().in(UserIdentity::getUserId, userIds)
        );
        identities.forEach(identity -> identityMap.put(identity.getUserId(), identity));

        // 按认证状态筛选
        List<TeacherListVO> teacherList = users.stream()
            .map(user -> {
                TeacherListVO vo = new TeacherListVO();
                UserProfile profile = profileMap.get(user.getId());
                UserIdentity identity = identityMap.get(user.getId());

                vo.setId(user.getId());
                vo.setAvatarUrl(user.getAvatarUrl());
                vo.setCreatedAt(user.getCreatedAt());
                vo.setIsOnline(false);
                vo.setVerified(identity != null && "APPROVED".equals(identity.getStatus()));

                if (profile != null) {
                    vo.setRealName(profile.getRealName());
                    vo.setSchool(profile.getSchool());
                    vo.setEducation(profile.getEducation());
                    vo.setIntro(profile.getIntro());
                    vo.setExperienceYears(profile.getExperienceYears());
                    vo.setHourlyRate(profile.getHourlyRate() != null ? profile.getHourlyRate() : BigDecimal.ZERO);

                    if (StrUtil.isNotBlank(profile.getSubjects())) {
                        vo.setSubjects(Arrays.asList(profile.getSubjects().split(",")));
                    }
                }

                vo.setRating(BigDecimal.valueOf(4.8));
                vo.setReviewCount(100);
                vo.setOrderCount(50);

                return vo;
            })
            .filter(teacher -> {
                if (StrUtil.isNotBlank(queryDTO.getIdentityStatus())) {
                    UserIdentity identity = identityMap.get(teacher.getId());
                    String status = identity != null ? identity.getStatus() : "NOT_SUBMITTED";
                    return status.equals(queryDTO.getIdentityStatus());
                }
                return true;
            })
            .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("list", teacherList);
        result.put("total", userPage.getTotal());
        result.put("page", queryDTO.getPage());
        result.put("size", queryDTO.getSize());

        return result;
    }

    @Override
    @Transactional
    public void adminUpdateTeacherStatus(Long id, String status) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new BusinessException(ResultCode.USER_NOT_FOUND);
        }

        if (!user.getRoles().contains("TEACHER")) {
            throw new BusinessException("该用户不是教员");
        }

        user.setStatus(status);
        userMapper.updateById(user);

        log.info("管理员更新教员状态: userId={}, status={}", id, status);
    }

    @Override
    public List<Map<String, Object>> getPendingAuditList() {
        List<UserIdentity> identities = userIdentityMapper.selectList(
            new LambdaQueryWrapper<UserIdentity>()
                .eq(UserIdentity::getStatus, "PENDING")
                .orderByAsc(UserIdentity::getSubmittedAt)
        );

        List<Long> userIds = identities.stream()
            .map(UserIdentity::getUserId)
            .collect(Collectors.toList());

        if (userIds.isEmpty()) {
            return new ArrayList<>();
        }

        List<User> users = userMapper.selectBatchIds(userIds);
        Map<Long, User> userMap = users.stream()
            .collect(Collectors.toMap(User::getId, u -> u));

        List<UserProfile> profiles = userProfileMapper.selectList(
            new LambdaQueryWrapper<UserProfile>().in(UserProfile::getUserId, userIds)
        );
        Map<Long, UserProfile> profileMap = profiles.stream()
            .collect(Collectors.toMap(UserProfile::getUserId, p -> p));

        return identities.stream().map(identity -> {
            Map<String, Object> map = new HashMap<>();
            User user = userMap.get(identity.getUserId());
            UserProfile profile = profileMap.get(identity.getUserId());

            map.put("userId", identity.getUserId());
            map.put("realName", profile != null ? profile.getRealName() : user.getUsername());
            map.put("mobile", user.getMobile());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("school", profile != null ? profile.getSchool() : "");
            map.put("education", profile != null ? profile.getEducation() : "");
            map.put("subjects", profile != null ? profile.getSubjects() : "");
            map.put("idFrontPath", identity.getIdFrontPath());
            map.put("idBackPath", identity.getIdBackPath());
            map.put("selfiePath", identity.getSelfiePath());
            map.put("submittedAt", identity.getSubmittedAt());
            map.put("auditedAt", identity.getAuditedAt());
            map.put("auditNote", identity.getAuditNote());

            return map;
        }).collect(Collectors.toList());
    }

    @Override
    public List<Map<String, Object>> getAuditListByStatus(String status) {
        List<UserIdentity> identities = userIdentityMapper.selectList(
            new LambdaQueryWrapper<UserIdentity>()
                .eq(UserIdentity::getStatus, status)
                .orderByDesc(UserIdentity::getAuditedAt)
        );

        List<Long> userIds = identities.stream()
            .map(UserIdentity::getUserId)
            .collect(Collectors.toList());

        if (userIds.isEmpty()) {
            return new ArrayList<>();
        }

        List<User> users = userMapper.selectBatchIds(userIds);
        Map<Long, User> userMap = users.stream()
            .collect(Collectors.toMap(User::getId, u -> u));

        List<UserProfile> profiles = userProfileMapper.selectList(
            new LambdaQueryWrapper<UserProfile>().in(UserProfile::getUserId, userIds)
        );
        Map<Long, UserProfile> profileMap = profiles.stream()
            .collect(Collectors.toMap(UserProfile::getUserId, p -> p));

        return identities.stream().map(identity -> {
            Map<String, Object> map = new HashMap<>();
            User user = userMap.get(identity.getUserId());
            UserProfile profile = profileMap.get(identity.getUserId());

            map.put("userId", identity.getUserId());
            map.put("realName", profile != null ? profile.getRealName() : user.getUsername());
            map.put("mobile", user.getMobile());
            map.put("avatarUrl", user.getAvatarUrl());
            map.put("school", profile != null ? profile.getSchool() : "");
            map.put("education", profile != null ? profile.getEducation() : "");
            map.put("subjects", profile != null ? profile.getSubjects() : "");
            map.put("auditedAt", identity.getAuditedAt());
            map.put("auditNote", identity.getAuditNote());

            return map;
        }).collect(Collectors.toList());
    }

    @Override
    @Transactional
    public void auditTeacherIdentity(AuditIdentityDTO auditDTO) {
        UserIdentity identity = userIdentityMapper.selectOne(
            new LambdaQueryWrapper<UserIdentity>()
                .eq(UserIdentity::getUserId, auditDTO.getUserId())
        );

        if (identity == null) {
            throw new BusinessException("未找到认证申请");
        }

        if (!"PENDING".equals(identity.getStatus())) {
            throw new BusinessException("该申请已审核");
        }

        identity.setStatus(auditDTO.getStatus());
        identity.setAuditNote(auditDTO.getAuditNote());
        identity.setAuditedAt(LocalDateTime.now());
        userIdentityMapper.updateById(identity);

        log.info("审核教员身份: userId={}, status={}, note={}",
            auditDTO.getUserId(), auditDTO.getStatus(), auditDTO.getAuditNote());
    }

    /**
     * 应用筛选条件
     */
    private List<TeacherListVO> applyFilters(List<TeacherListVO> list, TeacherQueryDTO queryDTO) {
        return list.stream()
            .filter(teacher -> {
                // 关键词筛选
                if (StrUtil.isNotBlank(queryDTO.getKeyword())) {
                    String keyword = queryDTO.getKeyword().toLowerCase();
                    boolean match = false;

                    if (StrUtil.isNotBlank(teacher.getRealName()) &&
                        teacher.getRealName().toLowerCase().contains(keyword)) {
                        match = true;
                    }

                    if (StrUtil.isNotBlank(teacher.getSchool()) &&
                        teacher.getSchool().toLowerCase().contains(keyword)) {
                        match = true;
                    }

                    if (teacher.getSubjects() != null &&
                        teacher.getSubjects().stream().anyMatch(s -> s.toLowerCase().contains(keyword))) {
                        match = true;
                    }

                    if (!match) return false;
                }

                // 年级筛选
                if (StrUtil.isNotBlank(queryDTO.getGrade()) && !queryDTO.getGrade().equals("全部")) {
                    if (teacher.getGrades() == null || !teacher.getGrades().contains(queryDTO.getGrade())) {
                        return false;
                    }
                }
                
                // 科目筛选
                if (StrUtil.isNotBlank(queryDTO.getSubject()) && !queryDTO.getSubject().equals("全部")) {
                    if (teacher.getSubjects() == null || !teacher.getSubjects().contains(queryDTO.getSubject())) {
                        return false;
                    }
                }

                // 价格筛选
//                if (queryDTO.getMinPrice() != null) {
//                    if (teacher.getHourlyRate() == null || teacher.getHourlyRate().compareTo(queryDTO.getMinPrice()) <= 0) {
//                        return false;
//                    }
//                }
//                if (queryDTO.getMaxPrice() != null) {
//                    if (teacher.getHourlyRate() == null || teacher.getHourlyRate().compareTo(queryDTO.getMaxPrice()) > 0) {
//                        return false;
//                    }
//                }

                // 经验筛选
                if (queryDTO.getMinExperience() != null &&
                    (teacher.getExperienceYears() == null || teacher.getExperienceYears() < queryDTO.getMinExperience())) {
                    return false;
                }

                // 评分筛选
                if (queryDTO.getMinRating() != null) {
                    if (teacher.getRating() == null || teacher.getRating().compareTo(queryDTO.getMinRating()) < 0) {
                        return false;
                    }
                }

                // 在线筛选
                if (Boolean.TRUE.equals(queryDTO.getOnlineOnly()) && !Boolean.TRUE.equals(teacher.getIsOnline())) {
                    return false;
                }

                return true;
            })
            .sorted((t1, t2) -> {
                // 排序
                if (StrUtil.isNotBlank(queryDTO.getSortBy())) {
                    int order = "DESC".equalsIgnoreCase(queryDTO.getSortOrder()) ? -1 : 1;

                    switch (queryDTO.getSortBy()) {
                        case "rating":
                            BigDecimal rating1 = t1.getRating() != null ? t1.getRating() : BigDecimal.ZERO;
                            BigDecimal rating2 = t2.getRating() != null ? t2.getRating() : BigDecimal.ZERO;
                            return order * rating2.compareTo(rating1);
                        case "price":
                            BigDecimal price1 = t1.getHourlyRate() != null ? t1.getHourlyRate() : BigDecimal.ZERO;
                            BigDecimal price2 = t2.getHourlyRate() != null ? t2.getHourlyRate() : BigDecimal.ZERO;
                            return order * price2.compareTo(price1);
                        case "experience":
                            return order * Integer.compare(
                                t2.getExperienceYears() != null ? t2.getExperienceYears() : 0,
                                t1.getExperienceYears() != null ? t1.getExperienceYears() : 0
                            );
                    }
                }
                return 0;
            })
            .collect(Collectors.toList());
    }
}

